package com.lizard.schedule.utils;

import android.os.Environment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

/**
 * Created by wangyiqian on 16/6/11.
 */

public class CrashUtil {
    public static final String CRASH_LOG_PATH = "/schedule/dev/crash_log/";

    public static void init() {

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                writeCrashInfoToFile(ex);

                System.exit(0);
            }
        });
    }

    /**
     * 将崩溃写入文件系统
     *
     * @param ex
     */
    private static void writeCrashInfoToFile(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String sdcardPath = Environment.getExternalStorageDirectory().getPath();
            String filePath = sdcardPath + CRASH_LOG_PATH;
            writeLog(sb.toString(), filePath);
        }
    }

    private static String writeLog(String log, String name) {
        String time = new Date().toString().replace(" ", "");
        String filename = name + time + ".log";
        File file = new File(filename);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            file.createNewFile();
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(log);
            bw.newLine();
            bw.close();
            fw.close();
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
